package listen

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"github.com/gookit/event"
	"github.com/thinkeridea/go-extend/exunicode/exutf8"
	"go.uber.org/zap"
	"strings"
	"unicode/utf8"
	"vueBasic/app/admin/filter"
	"vueBasic/app/common/model"
	"vueBasic/extend/conv"
	"vueBasic/extend/utils"
	"vueBasic/global"
)

// 监听异常事件
func ExceptionLogEventListen(e event.Event) error {

	handle := e.Data()["handle"].(*gin.Context)

	var content map[string]interface{}
	handle.ShouldBind(&content)

	for key, val := range content {
		if utf8.RuneCountInString(conv.String(val)) > 200 {
			content[key] = exutf8.RuneSubString(conv.String(val), 0, 200)
		}
	}

	str, _ := json.Marshal(content)
	var logData filter.AdminLogAddReq
	logData.ApplicationName = strings.Split(strings.TrimLeft(handle.Request.RequestURI, "/"), "/")[0]
	logData.Username = "admin"
	logData.Ip = utils.GetClientIP(handle)
	logData.Url = "http://" + handle.Request.Host + handle.Request.RequestURI
	logData.Useragent = handle.Request.UserAgent()
	logData.Type = 3
	logData.CreateTime = conv.NowUnix()
	logData.Content = string(str)
	logData.Errmsg = conv.String(e.Data()["errMsg"])

	if err := model.AdminLogM.Add(logData); err != nil {
		global.LOG.Error(err.Error())
	}

	global.LOG.Error("[Recovery from panic]",
		zap.Any("error", e.Data()["errMsg"]),
		zap.String("request", handle.Request.Method),
		zap.String("request", handle.Request.RequestURI),
	)

	return nil
}
